package com.suo.web;

import com.alibaba.fastjson.JSON;
import com.suo.mapper.UserMapper;
import com.suo.pojo.User;
import com.suo.util.SqlSessionFactoryUtils;
import org.apache.ibatis.session.SqlSession;
import org.apache.ibatis.session.SqlSessionFactory;

import javax.servlet.*;
import javax.servlet.http.*;
import javax.servlet.annotation.*;
import java.io.IOException;

@WebServlet(name = "registServlet", value = "/registServlet")
public class RegistServlet extends HttpServlet {
    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        String kaptcha_session_key = (String)request.getSession().getAttribute("KAPTCHA_SESSION_KEY");
        request.getSession().removeAttribute("KAPTCHA_SESSION_KEY");

        String code = request.getParameter("code");

        if(kaptcha_session_key.equalsIgnoreCase(code)) {

            SqlSessionFactory sqlSessionFactory = SqlSessionFactoryUtils.getSqlSessionFactory();

            SqlSession sqlSession = sqlSessionFactory.openSession();

            UserMapper mapper = sqlSession.getMapper(UserMapper.class);

            String userStr = request.getReader().readLine();

            User user = JSON.parseObject(userStr, User.class);

            if(!("".equals(user.getName()) && "".equals(user.getPassword()) && "".equals(user.getEmail()))) {
                mapper.add(user);

                sqlSession.commit();

                sqlSession.close();

                response.getWriter().write("1");
            }

        }

    }

    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        this.doGet(request, response);
    }
}
